package com.wt.struggle.goodbye

import android.app.AlertDialog
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.main.activity.SendActivity
import com.wt.struggle.goodbye.main.activity.SendTieActivity
import com.wt.struggle.goodbye.main.fragment.MainPageFragment
import com.wt.struggle.goodbye.message.MessageFragment
import com.wt.struggle.goodbye.user.UserFragment
import com.wt.struggle.goodbye.user.activity.LoginActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.pop_view_layout.view.*
import org.json.JSONObject
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.sq.fragment.QuQuanClassifyFragment
import com.xin.lv.yang.utils.utils.StatusBarUtil
import kotlinx.android.synthetic.main.tab_item_layout.*


class MainActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.GET_USER_INFO -> {
                if (netInfo.code == Config.SUCCESS) {
                    val jsonObject = JSONObject(netInfo.dataResult)
                    val userId = jsonObject.optInt("id")
                    Share.saveUid(this@MainActivity, userId)

                }
            }

            Send.LOGIN_ACTIVITY -> {

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    if (result != null && result != "") {
                        val json = JSONObject(result)
                        val uuid = json.optString("uuid")

                        val userId = json.optInt("id")
                        Share.saveUid(this@MainActivity, userId)

                        Share.saveUuid(this, uuid)

                    }
                }
            }
        }

    }

    var manager: FragmentManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        manager = supportFragmentManager

        initClick()

        initFirst()

    }

    override fun onResume() {
        super.onResume()

        token = Share.getToken(this)

        if (token != "") {
            send!!.loginActivity(token, Share.getUmToken(this@MainActivity), handler)
        }
    }

    var fragmentList = arrayListOf<ProV4Fragment>(
        MainPageFragment(), QuQuanClassifyFragment(),
        MessageFragment(), UserFragment()
    )


    private fun initFirst() {
        customViewPager.adapter = object : FragmentStatePagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int): Fragment = fragmentList[position]

            override fun getCount(): Int = fragmentList.size

        }

        val code = intent.getIntExtra("code", 1)

        if (code == 2) {
            showNum(1)
            customViewPager.currentItem = 2
        } else {
            customViewPager.currentItem = 0
        }


    }

    private fun initClick() {

        imageAdd.setOnClickListener {

            if (Share.getToken(this) != "") {

                val intent = Intent(this@MainActivity, SendTieActivity::class.java)
                startActivity(intent)

            } else {
                val intent = Intent(this@MainActivity, LoginActivity::class.java)
                startActivity(intent)
            }

        }

        mainTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                val ppp = tab!!.position

                when (ppp) {
                    0 -> {
                        StatusBarUtil.setStatusBarLightMode(window, true)
                        customViewPager.currentItem = 0
                    }
                    1 -> {
                        StatusBarUtil.setStatusBarLightMode(window, true)
                        customViewPager.currentItem = 1
                    }
                    3 -> {
                        StatusBarUtil.setStatusBarLightMode(window, true)
                        customViewPager.currentItem = 2
                    }

                    4 -> {

                        StatusBarUtil.setStatusBarLightMode(window, true)
                        customViewPager.currentItem = 3

                    }
                }
            }
        })

    }

    fun showNum(num: Int) {
        if (num != 0) {
            tvMessageNum.visibility = View.VISIBLE
        } else {
            tvMessageNum.visibility = View.GONE
        }

        tvMessageNum.text = num.toString()
    }


    /**
     * 选择弹窗
     */
    private fun showPopChoose() {
        val popView = layoutInflater.inflate(R.layout.pop_view_layout, null)

        val w = getW() * 4 / 5
        val pop = PopupWindow(popView, w, LinearLayout.LayoutParams.WRAP_CONTENT, true)
        pop.animationStyle = R.style.pop_anima
        pop.isOutsideTouchable = false
        pop.setBackgroundDrawable(BitmapDrawable())

        pop.setOnDismissListener {
            setAlpha(1f)
        }

        pop.showAtLocation(popView, Gravity.BOTTOM, 0, 170)
        setAlpha(0.6f)

        popView.tvSendFriend.setOnClickListener {
            setAlpha(1f)
            pop.dismiss()
            val intent = Intent(this@MainActivity, SendActivity::class.java)
            startActivity(intent)

        }

        popView.tvSendTie.setOnClickListener {
            setAlpha(1f)
            pop.dismiss()

            if (Share.getToken(this) != "") {
                val intent = Intent(this@MainActivity, SendTieActivity::class.java)
                startActivity(intent)
            } else {
                val intent = Intent(this@MainActivity, LoginActivity::class.java)
                startActivity(intent)
            }

        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event!!.action == KeyEvent.ACTION_DOWN) {

            if (fragmentManager.backStackEntryCount != 0) {
                fragmentManager!!.popBackStack()
            } else {
                val build = AlertDialog.Builder(this)
                build.setTitle("提示").setMessage("是否退出?")
                    .setPositiveButton("退出") { dialog, p ->
                        finish()
                    }.setNegativeButton("取消") { _, _ -> }.show()
            }
        }

        return true
    }


}
